package com.rahms.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rahms.common.constant.CacheConstant;
import com.rahms.pojo.entity.User;
import com.rahms.server.mapper.UserMapper;
import com.rahms.server.service.UserService;
import com.rahms.server.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Override
    @Cacheable(value = "user", key = "#username", unless = "#result == null")
    public User getUserByUsername(String username) {
        // 先尝试从缓存获取
        String cacheKey = CacheConstant.USER_INFO_CACHE + username;
        User cachedUser = redisUtil.get(cacheKey, User.class);
        if (cachedUser != null) {
            return cachedUser;
        }
        
        // 缓存未命中，从数据库查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = this.getOne(queryWrapper);
        
        // 将结果缓存
        if (user != null) {
            redisUtil.set(cacheKey, user, CacheConstant.CACHE_EXPIRE_MEDIUM, TimeUnit.SECONDS);
        }
        
        return user;
    }
    
    @Override
    @Cacheable(value = "user", key = "#userId", unless = "#result == null")
    public User getUserById(Long userId) {
        // 先尝试从缓存获取
        String cacheKey = CacheConstant.USER_INFO_CACHE + userId;
        User cachedUser = redisUtil.get(cacheKey, User.class);
        if (cachedUser != null) {
            return cachedUser;
        }
        
        // 缓存未命中，从数据库查询
        User user = this.getById(userId);
        
        // 将结果缓存
        if (user != null) {
            redisUtil.set(cacheKey, user, CacheConstant.CACHE_EXPIRE_MEDIUM, TimeUnit.SECONDS);
        }
        
        return user;
    }
    
    @Override
    @Cacheable(value = "userList", key = "#role + ':' + #keyword", unless = "#result == null || #result.isEmpty()")
    public List<User> getUserList(String role, String keyword) {
        // 先尝试从缓存获取
        String cacheKey = CacheConstant.USER_LIST_CACHE + role + ":" + keyword;
        List<User> cachedList = redisUtil.get(cacheKey, List.class);
        if (cachedList != null) {
            return cachedList;
        }
        
        // 缓存未命中，从数据库查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (role != null && !role.isEmpty()) {
            queryWrapper.eq(User::getRole, role);
        }
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like(User::getUsername, keyword);
        }
        List<User> userList = this.list(queryWrapper);
        
        // 将结果缓存
        if (userList != null && !userList.isEmpty()) {
            redisUtil.set(cacheKey, userList, CacheConstant.CACHE_EXPIRE_MEDIUM, TimeUnit.SECONDS);
        }
        
        return userList;
    }
    
    @Override
    @CacheEvict(value = {"user", "userList"}, allEntries = true)
    public void clearUserCache(Long userId) {
        // 清除特定用户的缓存
        redisUtil.delete(CacheConstant.USER_INFO_CACHE + userId);
        redisUtil.delete(CacheConstant.USER_LIST_CACHE + "*");
    }
    
    @Override
    public boolean save(User user) {
        boolean result = super.save(user);
        if (result) {
            // 保存成功后清除相关缓存
            clearUserCache(user.getUserId());
        }
        return result;
    }
    
    @Override
    public boolean updateById(User user) {
        boolean result = super.updateById(user);
        if (result) {
            // 更新成功后清除相关缓存
            clearUserCache(user.getUserId());
        }
        return result;
    }
    
    @Override
    public boolean removeById(Long userId) {
        boolean result = super.removeById(userId);
        if (result) {
            // 删除成功后清除相关缓存
            clearUserCache(userId);
        }
        return result;
    }
}